package com.mindao.app.weixin.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mindao.app.common.spring.model.BaseModel;
import com.mindao.app.common.spring.service.BaseService;
import com.mindao.app.ea.model.Role;
import com.mindao.app.ea.model.ZTreeNodeVO;
import com.mindao.app.weixin.model.WxmpButton;

/**
 * 微信菜单管理
 * @author liguocai
 *
 */
@Service ("wxmpButtonService")
public class WxmpButtonServiceImpl implements WxmpButtonService {
	private final Logger log = LoggerFactory.getLogger(WxmpButtonServiceImpl.class);
	@javax.annotation.Resource(name = "baseService")
	private BaseService baseService;

	@Override
	public List<ZTreeNodeVO> loadZtreeData(Integer disabled, String clickEvent) {
		// TODO Auto-generated method stub
		String baseSql = "from WxmpButton t where   t.status>"
				+ BaseModel.STATUS_REMOVED;
		String rootSql = baseSql + " and t.parentModel is null";
		String orderSql = " order by t.sortNob";
		if (disabled != null) {
			if (disabled == 1) {
				rootSql = rootSql + " and t.disabled=" + disabled;
			} else {
				rootSql = rootSql + " and (t.disabled=" + disabled
						+ " or t.disabled is null)";
			}
		}
		List<WxmpButton> rootList = baseService.find(rootSql + orderSql);
		// 其他非根节点
		String otherSql = baseSql + " and t.parentModel is not null";
		orderSql = " order by t.parentModel.id,t.sortNob";
		if (disabled != null) {
			// otherSql=otherSql+" and t.disabled="+disabled
			// +" order by t.parentModel.id,t.sortNob";
			if (disabled == 1) {
				otherSql = otherSql + " and t.disabled=" + disabled;
			} else {
				otherSql = otherSql
						+ " and ( t.disabled is null  or t.disabled="
						+ disabled + ")";
			}
		}
		List<WxmpButton> otherList = baseService.find(otherSql + orderSql);

		rootList.addAll(otherList);
		return transZTreeNodes(rootList, clickEvent);
	}

	/**
	 * 业务对象转ztreenode
	 * 
	 * @param list
	 * @param clickEvent
	 * @return
	 */
	public List<ZTreeNodeVO> transZTreeNodes(List<WxmpButton> list,
			String clickEvent) {
		List<ZTreeNodeVO> nodes = new ArrayList<ZTreeNodeVO>(list.size());
		for (WxmpButton o : list) {
			Long pId = o.getParentModel() == null ? 0 : o.getParentModel()
					.getId();
			ZTreeNodeVO nd = new ZTreeNodeVO(o.getId(), pId, o.getName());
			if (clickEvent != null) {
				String tmps = clickEvent.replaceAll("\\{SID\\}",
						o.getId().toString()).replaceAll("\\{pSid\\}",
						pId.toString());
				nd.setClick(tmps);
			}
			nodes.add(nd);
		}
		return nodes;
	}

	@Override
	public Long getNextSortNo(Long parentId) {
		// TODO Auto-generated method stub
		List<WxmpButton> list = findByParentId(null, parentId);
		long index = 1;
		for (WxmpButton wxmpButton : list) {
			if (wxmpButton.getSortNob() == null
					|| wxmpButton.getSortNob().longValue() != index) {
				wxmpButton.setSortNob(index);
				baseService.update(wxmpButton);
			}
			index++;
		}
		return index;
	}

	@Override
	public boolean move(Long id, Long parentId, boolean upside) {
		// TODO Auto-generated method stub
		WxmpButton data = (WxmpButton) baseService.loadById(WxmpButton.class,
				Long.valueOf(id));
		List<WxmpButton> list = findByParentId(null, parentId);
		long index = 1;
		for (WxmpButton wxmpButton : list) {
			if (wxmpButton.getSortNob() == null
					|| wxmpButton.getSortNob().longValue() != index) {
				wxmpButton.setSortNob(index);
				baseService.update(wxmpButton);
			}
			if (data.getId().equals(wxmpButton.getId())) {
				data.setSortNob(index);
			}
			index++;
		}
		// 移动
		Long sortNob = data.getSortNob();
		if (upside) {
			if (sortNob > 1) {
				WxmpButton upData = list
						.get(Long.valueOf(sortNob).intValue() - 2);
				upData.setSortNob(sortNob);
				baseService.update(upData);

				data.setSortNob(sortNob - 1);
				baseService.update(data);
			}
		} else {
			if (sortNob < list.size()) {
				WxmpButton downData = list.get(Long.valueOf(sortNob).intValue());
				downData.setSortNob(sortNob);
				baseService.update(downData);

				data.setSortNob(sortNob + 1);
				baseService.update(data);
			}
		}

		return true;
	}

	@Override
	public List<WxmpButton> findByParentId(Integer disabled, Long parentId) {
		// TODO Auto-generated method stub
		String baseSql = "from WxmpButton t where   t.status>"
				+ BaseModel.STATUS_REMOVED;
		String sql = null;
		if (parentId == null) {
			sql = baseSql + " and  t.parentModel is null";
		} else {
			sql = baseSql + " and  t.parentModel.id=" + parentId;
		}
		if (disabled != null) {
			if (disabled == 1) {
				sql = sql + " and t.disabled=" + disabled;
			} else {
				sql = sql + " and (t.disabled=" + disabled
						+ " or t.disabled is null)";
			}
		}
		List<WxmpButton> list = baseService.find(sql + " order by  t.sortNob");
		return list;
	}

	@Override
	public boolean deleteResursively(Long id) {
		// TODO Auto-generated method stub
		// Set<Long> deleteIdSet=new HashSet<Long>();
		WxmpButton obj = (WxmpButton) baseService.loadById(WxmpButton.class, id);
		baseService.delete(obj);
		// 删除相关角色
		List<Role> relRoleList = baseService.find(
				"from Role t where t.roleType=? and t.wxmpButton.id=?",
				new Object[] { Role.TYPE_ORG_REL, Long.valueOf(id) });
 
		// 删除子组织
		List<WxmpButton> list = findByParentId(null, id);
		for (WxmpButton wxmpButton : list) {
			deleteResursively(wxmpButton.getId());
		}
		return true;
	}

	@Override
	public boolean judgeParentRelation(WxmpButton child, WxmpButton parent) {
		// TODO Auto-generated method stub
		if (parent == null) {
			return true;
		}
		WxmpButton tmpObj = parent;
		if (tmpObj.getId().equals(child.getId())) {
			return false;
		}
		while (tmpObj.getParentModel() != null) {
			if (tmpObj.getParentModel().getId().equals(child.getId())) {
				return false;
			} else {
				tmpObj = tmpObj.getParentModel();
			}
		}
		return true;
	}

	@Override
	public boolean judgeMoveDownable(WxmpButton org) {
		// TODO Auto-generated method stub
		if (org==null){
			return false;
		}
		List brothertList = this.findByParentId(null,
				org.getParentModel() == null ? null : org.getParentModel()
						.getId());
		if (brothertList.size() == org.getSortNob().intValue()) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public boolean judgeMoveUpable(WxmpButton org) {
		// TODO Auto-generated method stub
		if (org==null){
			return false;
		}
		if (org.getSortNob().intValue() == 1) {
			return false;
		} else {
			return true;
		}
	}
}
